<template>
  <div class="container">
    <van-sticky>
      <van-nav-bar title="❤️ 转票" left-arrow @click-left="onClickLeft" />
      <van-search
        v-model="keyword"
        placeholder="请搜索演出进行卖票"
        left-icon=""
        show-action
        @keydown.enter="onSearch(keyword)"
        @clear="onClear"
      >
        <template #action
          ><van-icon name="search" size="20" class="search" @click="onSearch(keyword)"
        /></template>
      </van-search>
    </van-sticky>

    <div class="search-history" v-if="searchHistory.length > 0 && results && results.length === 0">
      <div class="title">
        <span>历史搜索</span> <van-icon name="delete-o" size="18" @click="removeHistory" />
      </div>
      <div class="search-list">
        <template v-for="(item, index) in searchHistory" :key="index">
          <div class="search-item" @click="onSearch(item)">{{ item }}</div>
        </template>
      </div>
    </div>

    <div class="search-result" v-if="results && results.length > 0">
      <van-list
        v-model:loading="listLoading"
        :finished="listFinished"
        finished-text="没有更多了"
        :immediateCheck="false"
        @load="onLoad"
      >
        <ul class="result-list">
          <template v-for="result in results" :key="result.showOID">
            <li class="result-item" @click="goToTransferDetail(result)">
              <div class="left">
                <div class="cover">
                  <img :src="result.posterURL" class="thumb" />
                </div>
              </div>
              <div class="right">
                <div class="title">{{ result.showName }}</div>
                <div class="date-venue">
                  <div class="ShowTime">
                    {{ formatShowTime(result.firstShowTime, result.lastShowTime) }}
                  </div>
                  <div class="venue">{{ result.venueName }}</div>
                </div>
                <div class="result-button">
                  <van-button type="primary" round size="small" color="#FF1D41"
                    >我要转票</van-button
                  >
                </div>
              </div>
            </li>
          </template>
        </ul>
      </van-list>
    </div>

    <van-empty image="search" image-size="80" description="暂无相关演出" v-if="results === null">
      <div class="tip">建议您修改关键字后重新搜索</div>
    </van-empty>
  </div>
</template>

<script setup>
import { fetchTourSiteTicketTransferSearch } from '@/api/index.js'
import { computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
import { useStore } from '@/stores/index.js'

const store = useStore()

const cityId = computed(() => store.currentCity.cityId)

const listLoading = ref(false)
const listFinished = ref(false)

const keyword = ref('')

// 添加历史搜索记录的响应式变量
const searchHistory = ref([])

onMounted(() => {
  const savedHistory = localStorage.getItem('transferSearchHistory')
  if (savedHistory) {
    searchHistory.value = JSON.parse(savedHistory)
  }
})

const length = ref(10)
const pageNum = ref(1)
const offset = computed(() => (pageNum.value - 1) * length.value)

const results = ref([])
const currentCount = ref(0)

// 格式化时间
const formatShowTime = (firstShowTime, lastShowTime) => {
  if (firstShowTime === lastShowTime) {
    return firstShowTime.split('T')[0]
  }
  return firstShowTime.split('T')[0] + '~' + lastShowTime.split('T')[0]
}

// 返回前一页
const onClickLeft = () => {
  router.back()
}

// 搜索
const onSearch = (_keyword) => {
  keyword.value = _keyword
  pageNum.value = 1
  getTourSiteTicketTransferSearch(cityId.value, _keyword, length.value, offset.value)
  handleSearchHistory(_keyword)
}
//清除搜索关键词和搜索结果
// 显示搜索历史
const onClear = () => {
  results.value = []
  listFinished.value = false
}

// 移除历史搜索记录
const removeHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('transferSearchHistory')
}

// 添加历史搜索记录
const handleSearchHistory = (_keyword) => {
  const keyword = _keyword.trim()

  // 过滤掉重复的关键词
  const filteredHistory = searchHistory.value.filter((item) => item !== keyword)
  // 将新的关键词添加到历史记录的开头
  searchHistory.value = [keyword, ...filteredHistory]
  // 如果历史记录超过20条，只保留最近的20条
  if (searchHistory.value.length > 20) {
    searchHistory.value = searchHistory.value.slice(0, 20)
  }
  // 保存到 localStorage
  localStorage.setItem('transferSearchHistory', JSON.stringify(searchHistory.value))
}

const onLoad = () => {
  if (currentCount.value < length.value) {
    listLoading.value = false
    listFinished.value = true
    return
  } else {
    pageNum.value++
    getTourSiteTicketTransferSearch(cityId.value, keyword.value, length.value, offset.value)
  }
}

const getTourSiteTicketTransferSearch = async (cityId, keyword, length, offset) => {
  const trimKeyword = keyword.trim()
  try {
    listLoading.value = true
    listFinished.value = false
    const {
      statusCode,
      pagination: { count },
      data,
    } = await fetchTourSiteTicketTransferSearch(cityId, trimKeyword, length, offset)
    if (statusCode === 200) {
      if (pageNum.value === 1) {
        results.value = data
      } else {
        results.value.push(...data)
      }
      currentCount.value = count
    }
  } catch (error) {
    console.log('搜索错误哦', error)
  } finally {
    listLoading.value = false
  }
}

const goToTransferDetail = (transfer) => {
  store.setTransferTicket(transfer.showOID, transfer.showName, transfer.posterURL)
  router.push({ path: '/transfer-detail', query: { showId: transfer.showOID } })
}
</script>

<style scoped lang="scss">
.container {
  :deep(.van-field__value) {
    width: 100%;
  }

  :deep(.van-search__action) {
    display: flex;
    align-items: center;
  }

  .search-history {
    .title {
      padding: 10px 15px;
      font-size: 14px;
      color: #333;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .search-list {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 10px;
      padding: 0 15px;

      .search-item {
        padding: 4px 6px;
        border: 1px solid rgba(0, 0, 0, 0.04);
        border-radius: 4px;
        font-size: 13px;
        background-color: #f7f8fa;
        color: #999;
      }
    }
  }

  .search-result {
    padding: 0 15px;
    // margin-top: 20px;

    .van-list {
      // margin-bottom: 50px;

      .result-list {
        list-style: none;
        display: flex;
        flex-direction: column;

        .result-item {
          display: flex;
          align-items: flex-start;
          justify-content: flex-start;
          gap: 10px;
          padding: 10px 0;
          border-bottom: 1px solid rgba(0, 0, 0, 0.04);

          &::first-child {
            border-top: 1px solid rgba(0, 0, 0, 0.04);
          }

          .left {
            .cover {
              width: 100px;
              height: 130px;
              overflow: hidden;
              border-radius: 4px;

              .thumb {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
          }

          .right {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            height: 130px;
            justify-content: space-between;

            .title {
              font-size: 17px;
              font-weight: 500;
              //文字最多显示两行
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: normal;
            }

            .date-venue {
              .ShowTime {
                color: #737373;
                font-size: 12px;
                font-weight: 400;
              }

              .venue {
                color: #737373;
                font-size: 12px;
                font-weight: 400;
              }
            }

            .result-button {
              margin: 0 0 0 auto;

              .van-button {
                margin: 0 0 0 auto;
              }
            }
          }
        }
      }
    }
  }

  :deep(.van-empty__bottom) {
    margin-top: 0;

    .tip {
      font-size: 12px;
      color: #666;
    }
  }
}
</style>
